package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理支付超时订单
     */
    //@Scheduled(cron ="0 * * * * ?" )
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void processTimeOutOrder(){
        log.info("处理支付超时订单时间{}", LocalDateTime.now());
        Integer status= Orders.PENDING_PAYMENT;
        LocalDateTime orderTime=LocalDateTime.now().plusMinutes(-15);
        //获取超时订单
        List<Orders> ordersList=orderMapper.selectByStatusAndOrderTime(status,orderTime);
        //对ordersList进行判断
        if(ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }

    }
    /**
     * 处理一直处于派送中的订单
     */
    @Scheduled(cron ="0 0 02 * * ?" )
    public void processAlwaysDeliveryStatusOrder(){
        log.info("处理一直处于派送中的订单{}", LocalDateTime.now());
        Integer status= Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime orderTime=LocalDateTime.now().plusMinutes(-1);
        //获取凌晨两点之前一小时创建的处于派送状态订单
        List<Orders> ordersList=orderMapper.selectByStatusAndOrderTime(status,orderTime);
        //对ordersList进行判断
        if(ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
